<?php
namespace Api\Controller;
vendor('Firebase.JWT.JWT');

class QuestionController extends BaseController {
    public function askQuestion() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        if (!$_POST) {
            fail("需要post请求");
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $cid = $data['cid'];
        $qdesc = $data['qdesc'];
        if (!$cid) {
            fail_name('cid');
        }
        $qimgs = $data['qimgs'] ? $data['qimgs'] : '';
        $qrecord = $data['qrecord'] ? htmlspecialchars_decode($data['qrecord']) : '';
        if (!$qdesc && !$qimgs && !$qrecord) {
            fail('请您至少输入问题描述、图片、语音中的其中一项');
        }
        //2.查询这个用户的余额，检测是否可以支付这个问题的消费金额
        $m_user = M('user');
        $user_info = $m_user->field('uid,nick_name,balance')->where(array(
            'uid' => $uid
        ))->find();
        if (!$user_info) {
            fail('未找到用户');
        }
        $money = 1.99;//发一个问题扣除的金钱数
        if (floatval($user_info['balance']) < $money) {
            fail('金额不足，请联系 17600512681 进行充值(微信同号)');
        }
        //3.插入数据库
        M()->startTrans();
        $current_time = time();
        $res = M('question')->add(array(
            'cid'         => $cid,
            'uid'         => $uid,
            'qdesc'       => $qdesc,
            'qimgs'       => $qimgs,
            'qrecord'     => $qrecord,
            'pay_price'   => $money,
            'create_time' => $current_time,
            'update_time' => $current_time
        ));
        //扣除用户的余额
        $res_balance = M('user')->where(array(
            'uid' => $uid
        ))->save(array(
            'balance'     => array('exp', 'balance-' . $money),
            'update_time' => $current_time
        ));
        if (!$res || !$res_balance) {
            fail('提问失败，请重试');
            M()->rollback();
        } else {
            M()->commit();
            //计算发送类型
            $q_type = '文字';
            $message = '学生发起提问';
            if ($qdesc) {
                $message = mb_substr($qdesc, 0, (mb_strlen($qdesc, 'utf8') > 50 ? 50 : strlen($qdesc))) . '...';
            }
            if ($qdesc && $qimgs && $qrecord) {
                $q_type = '文字+图片+语音';
            } else if ($qdesc && $qimgs) {
                $q_type = '文字+图片';
            } else if ($qdesc && $qrecord) {
                $q_type = '文字+语音';
            } else if ($qdesc) {
                $q_type = '文字';
            } else if ($qimgs) {
                $q_type = '图片';
                $message = '图片';
            } else if ($qrecord) {
                $q_type = '语音';
                $message = '语音';
            }
            //发送通知给教师端
            $jpushSend = JpushAlertSend($user_info['nick_name'], $message, '', 'homework_new', array(
                "tag" => [$cid]
            ), 10 * 86400);//保留十天
            $m_wxformid = M('wxformid');
            $formidList = $m_wxformid->where(array(
                'uid'       => $uid,
                'use_state' => 0,
                'expire'    => array('gt', time()),
            ))->limit(0, 1)->order("expire asc")->select();
            if ($formidList) {
                $formBean = $formidList[0];
                $data = array(
                    "keyword1" => array( //下单人
                                         "value" => $user_info['nick_name'],
                                         "color" => "#232426"
                    ),
                    "keyword2" => array( //订单金额
                                         "value" => $money . '元',
                                         "color" => "#F40"
                    ),
                    "keyword3" => array( //订单内容
                                         "value" => $message,
                                         "color" => "#232426"
                    ),
                    "keyword4" => array( //订单状态
                                         "value" => '待接单',
                                         "color" => "#232426"
                    ),
                    "keyword5" => array( //下单时间
                                         "value" => date('Y年m月d日H点i分s秒', $current_time),
                                         "color" => "#f00"
                    ),
                    "keyword6" => array( //客服电话
                                         "value" => '17600512681',
                                         "color" => "#f40"
                    ),
                );
                $template_id = C('WX_QUESTION_ASK');
                sendWXMessage($template_id, $data, $formBean['formid'], $formBean['openid']);
                //置为废弃
                $m_wxformid->where(array(
                    'id' => $formBean['id']
                ))->save(array(
                    'use_state'   => 1,
                    'update_time' => $current_time
                ));
                $m_wxformid->where(array(
                    'use_state' => 1,
                    'expire'    => array('lt', time()),
                    '_logic'    => 'or'
                ))->delete();
            }
            succeed(null, '提问成功');
        }
    }

    //获取我的提问历史
    public function getQhistory() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $pageNo = $data['pageNo'];
        $pageSize = $data['pageSize'];
        if (!is_numeric($pageNo) || $pageNo < 0) {
            fail_name('pageNo');
        }
        if (!is_numeric($pageSize) || $pageSize < 0) {
            fail_name('pageSize');
        }
        $queryIndexStart = $pageNo * $pageSize;
        $qhistory_list = M()->query("select q.qid,q.cid,q.qdesc,q.qimgs,q.qrecord,q.process_state,q.create_time,c.cname,c1.cname as parent_name 
                                    from t_question q,t_category c,t_category as c1
                                    where q.uid='{$uid}' and q.cid=c.cid and c.cparent_id=c1.cid
                                    order by q.process_state asc, create_time desc
                                     limit {$queryIndexStart},{$pageSize};");
        //循环查出分类名称
        succeed(get_auto_data($qhistory_list, true));
    }

    public function uploadImage() {
        $uploadRes = uploadFile($_FILES['img'], 3 * 1024 * 1024, array(
            'jpg',
            'gif',
            'png',
            'jpeg'
        ), 'Public/upload/image/question/');
        if ($uploadRes['uploadstatus'] == 200) {
            succeed($uploadRes, '上传成功');
        } else {
            fail($uploadRes['msg']);
        }
    }

    public function uploadRecordFile() {
        $uploadRes = uploadFile($_FILES['record'], 1 * 1024 * 1024, array(
            'mp3',
            'amr'
        ), 'Public/upload/record/question/', false);
        if ($uploadRes['uploadstatus'] == 200) {
            succeed($uploadRes, '上传成功');
        } else {
            fail($uploadRes['msg']);
        }
    }

    public function getQuestions() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $qstate = $data['qstate'];  //0 待抢  1已抢 2已回复
        if (!is_numeric($qstate)) {
            fail_name('qstate');
        }
        $pageNo = $data['pageNo'];
        $pageSize = $data['pageSize'];
        if (!is_numeric($pageNo) || $pageNo < 0) {
            fail_name('pageNo');
        }
        if (!is_numeric($pageSize) || $pageSize < 0) {
            fail_name('pageSize');
        }
        $queryIndexStart = $pageNo * $pageSize;
        $sql = '';
        if ($qstate == 0) {
            //查询这个老师负责的科目
            $teacher_cate_info = M()->query("select t.uid,t.cid from t_teacher as t WHERE t.uid='{$uid}'");
            $sql = "select q.qid, q.cid,q.uid,q.qdesc,q.qimgs,q.process_state,q.qrecord,q.create_time,
                                    c.cname,c1.cname as parent_name,u.nick_name,u.head_img 
                                    from t_question as q,t_category as c,t_category as c1,t_user as u
                                    where q.cid='{$teacher_cate_info[0]['cid']}'
                                    and q.process_state={$qstate}
                                    and q.cid=c.cid
                                    and c.cparent_id=c1.cid
                                    and q.uid=u.uid
                                    order by create_time desc
                                     limit {$queryIndexStart},{$pageSize};";
        } else {
            $order_way = 'q.create_time';
            if ($qstate == 1) {
                //已领取
                $order_way = 'h.receive_time';
            } else if ($qstate == 2) {
                //已回复
                $order_way = 'h.answer_time';
            }
            $sql = "select q.qid, q.cid,q.uid,q.qdesc,q.qimgs,q.process_state,q.qrecord,q.create_time,
                                    c.cname,c1.cname as parent_name,u.nick_name,u.head_img 
                                    from t_qdeal_history as h, t_question as q,t_category as c,t_category as c1,t_user as u
                                    where h.uid='{$uid}'
                                    and h.process_state={$qstate}
                                    and h.qid=q.qid
                                    and q.cid=c.cid
                                    and c.cparent_id=c1.cid
                                    and q.uid=u.uid
                                    order by {$order_way} desc
                                     limit {$queryIndexStart},{$pageSize};";
        }
        $qhistory_list = M()->query($sql);
        //循环查出分类名称
        succeed(get_auto_data($qhistory_list, true));
    }

    public function receiveQuestion() {
        $uid = isLogin();
        if (!$uid) {
            fail_login('请登录后操作');
        }
        $data = get_auto_data($_REQUEST);
        //1.必填参数判断
        $qid = $data['qid'];
        if (!$qid) {
            fail_name('qid');
        }
        //2.更新提问的状态为已领取 process_state改为1 关于thinkphp连贯操作加锁的详细介绍lock 首先，数据库类型要是InnoDB，其次，加锁必须跟事务同时使用，还有，查询的时候都必须带锁
        $current_time = time();
        M()->startTrans();//开启事务
        $question = M('question');
        //查询这个提问的状态是否为待领取（0），只有是0的情况才能改成1
        $question_info = $question->lock(true)->field('qid,process_state')->where(array(
            'qid' => $qid
        ))->find();//加锁查询
        if (!$question_info) {
            M()->rollback();
            fail('未获取到提问记录');
        } else if ($question_info['process_state'] != 0) {
            //提示该提问已经被领取
            M()->rollback();
            fail('手速慢了点，再接再厉！');
        } else {
            //修改表的处理状态为已领取状态（1）
            $q_modify_res = $question->lock(true)->where(array(
                'qid' => $qid
            ))->save(array(
                'process_state' => 1,
                'update_time'   => $current_time
            ));
            //添加提问的处理记录
            $qhistory_add_res = M('qdeal_history')->add(array(
                'qid'           => $qid,
                'uid'           => $uid,
                'process_state' => 1,
                'receive_time'  => $current_time,
                'create_time'   => $current_time,
                'update_time'   => $current_time
            ));
            if (!$q_modify_res || !$qhistory_add_res) {
                //任何一个不成功就得回滚事物
                M()->rollback();
                fail('抢单失败，请重试');
                return;
            }
            //领取成功了
            M()->commit();//事务提交
            succeed(null, '抢单成功');
        }
    }
}